package base;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 发送同步消息:这种可靠性同步地发送方式使用的比较广泛，比如：重要的消息通知，短信通知。
 */
public class SyncProducer {

    public static void main(String[] args) throws Exception {
        //1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("114.55.126.232:9876");
        //3.启动producer
        producer.start();

        for (int i = 0; i < 10; i++) {
            //4.创建消息对象，指定主题Topic、Tag和消息体
            /**
             * 参数一：消息主题Topic
             * 参数二：消息Tag
             * 参数三：消息内容
             */
            Message msg = new Message("broker-b", "Tag1", ("Hello World" + i).getBytes());
            //延时发送
            msg.setDelayTimeLevel(2);
            // 设置一些属性
            msg.putUserProperty("a", String.valueOf(i));
            //5.发送消息
            SendResult result = producer.send(msg);
            //发送状态
            SendStatus status = result.getSendStatus();

//            String s = result.getMsgId();
//            int messageQueue = result.getMessageQueue().getQueueId();
            System.out.println("发送结果:" + result);


            /**
             * 发送批量消息
             */
//            String topic = "BatchTest";
//            List<Message> messages = new ArrayList<>();
//            messages.add(new Message(topic, "TagA", "OrderID001", "Hello world 0".getBytes()));
//            messages.add(new Message(topic, "TagA", "OrderID002", "Hello world 1".getBytes()));
//            messages.add(new Message(topic, "TagA", "OrderID003", "Hello world 2".getBytes()));
//            try {
//                producer.send(messages);
//            } catch (Exception e) {
//                e.printStackTrace();
//                //处理error
//            }
            //线程睡1秒
//            TimeUnit.SECONDS.sleep(1);
        }

        //6.关闭生产者producer
//        producer.setVipChannelEnabled(false);
        producer.shutdown();
    }
}
